package cn.com.doone.common.uc.web.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.doone.common.uc.utils.MessageUtils;
import cn.com.doone.common.uc.utils.PropertiesUtils;
import cn.com.doone.common.uc.utils.StringUtils;
import cn.com.doone.common.uc.web.BaseController;
import cn.com.doone.common.uc.web.service.AppService;
@Controller
@RequestMapping(value="/sync")
public class AppController extends BaseController{

	private final static Logger logger = LoggerFactory.getLogger(AppController.class);
	
	@Value("${style.path}")
	private String targetUrl;
	
	@Autowired
	private AppService appService;
	
	@Autowired
	private PropertiesUtils propertiesUtils;
	
	/**
	 * 验证client是否重复
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/validAppCode",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> validClient(HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		if(StringUtils.isNull(paramsMap.get("appCode"))) {
			resultMap.put("success", false);
			resultMap.put("message", "参数不能为空");
			return resultMap;
		}
		return appService.validClientId(paramsMap);
	}
	
	/**
	 * 查询应用分页列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/queryAppPageList",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> queryAppPageList(HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		if(StringUtils.isNull(paramsMap.get("page")) || StringUtils.isNull(paramsMap.get("limit"))) {
			resultMap.put("success", false);
			resultMap.put("message", MessageUtils.PARAMS_NULL);
			return resultMap;
		}
		return appService.queryAppPageList(paramsMap);
	}
	
	/**
	 * 添加应用
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addApp",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> registApp(HttpServletRequest request) throws Exception {
		//获取参数
		Map<String,Object> paramsMap = getParams(request);
		logger.info("获取参数:"+paramsMap);
		
		return appService.addApp(paramsMap);
	}
	
	/**
	 * 根据ID查应用信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/queryAppInfoById",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> queryAppInfoById(HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		if(StringUtils.isNull(paramsMap.get("appInfoId"))) {
			resultMap.put("success", false);
			resultMap.put("message", MessageUtils.PARAMS_NULL);
			return resultMap;
		}
		return appService.queryAppInfoById(paramsMap);
	}
	
	/**
	 * 修改应用
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editApp",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> editApp(HttpServletRequest request) throws Exception {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		if(StringUtils.isNull(paramsMap.get("appInfoId"))) {
			resultMap.put("success", false);
			resultMap.put("message", MessageUtils.PARAMS_NULL);
			return resultMap;
		}
		logger.info("获取参数:"+paramsMap);
		paramsMap.put("plainText", paramsMap.get("clientId"));
		return appService.updateApp(paramsMap);
	}
	
	/**
	 * 修改应用状态
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/changeAppStatus", method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> changeAppStatus(HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		if(StringUtils.isNull(paramsMap.get("appInfoId"))) {
			resultMap.put("success", true);
			resultMap.put("message", MessageUtils.PARAMS_NULL);
			return resultMap;
		}
		resultMap = appService.changeAppStatus(paramsMap);
		return resultMap;
	}
	
	/**
	 * 查询应用组授权关系
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/queryAppGroupAuthzTreeList",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> queryAppGroupAuthzTreeList(HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		if(StringUtils.isNull(paramsMap.get("appInfoId"))) {
			resultMap.put("success", true);
			resultMap.put("message", MessageUtils.PARAMS_NULL);
			return resultMap;
		}
		resultMap = appService.queryAppGroupAuthzTreeList(paramsMap);
		return resultMap;
	}
	
	/**
	 * 应用授权组
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/editAppGroupAuthz",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> editAppGroupAuthz(HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		if(StringUtils.isNull(paramsMap.get("appInfoId"))) {
			resultMap.put("success", true);
			resultMap.put("message", MessageUtils.PARAMS_NULL);
			return resultMap;
		}
		resultMap = appService.editAppGroupAuthz(paramsMap);
		return resultMap;
	}
	
	/**
	 * 删除应用
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/deleteApp",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> deleteApp(HttpServletRequest request) throws Exception {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = getParams(request);
		
		logger.info("获取参数:"+paramsMap);
		
		if(StringUtils.isNull(paramsMap.get("clientId")) || StringUtils.isNull(paramsMap.get("authenticator"))) {
			resultMap.put("success", false);
			resultMap.put("message", "参数不能为空");
			return resultMap;
		}
		paramsMap.put("plainText", paramsMap.get("clientId"));
		resultMap = appService.comparisonAuth(paramsMap);
		if(!resultMap.isEmpty()) {
			return resultMap;
		}
		
		return appService.deleteApp(paramsMap);
	}
	
	/**
	 * 样式文件上传
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadStyle",method = RequestMethod.POST)
	public @ResponseBody Map<String,Object> uploadStyle(HttpServletRequest request) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		try {
			if(ServletFileUpload.isMultipartContent(request)) {
				//设定内存可以存放文件的最大容量，单位字节，这里设置成10兆
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(1024*1024*10);
				
				ServletFileUpload upload = new ServletFileUpload(factory);
				//设置单个文件最大容量限制,这里限制2M
				upload.setFileSizeMax(1024*1024*2);
				//设置整个请求的上传容量限制,这里限制5M
				upload.setSizeMax(1024*1024*5);
				upload.setHeaderEncoding("UTF-8");
				
				int fileNum = 0;
				List<FileItem> items = upload.parseRequest(request);
				Iterator<FileItem> iterator = items.iterator();
				String fileName = "";
				FileItem uploadFile = null;
				while(iterator.hasNext()) {
					FileItem item = iterator.next();
					if(item.isFormField()) {		//普通表单属性
						paramsMap.put(item.getFieldName(), item.getString());
					}else {		//文件
						if(fileNum==0) {
							fileName = item.getName();
							String lastFileName = fileName.substring(fileName.lastIndexOf("\\.")+1);
							if("css".equals(lastFileName)) {
								resultMap.put("success", false);
								resultMap.put("msg", "不支持的文件类型");
								return resultMap;
							}
							paramsMap.put("fileName", fileName);
							uploadFile = item;
							fileNum ++;
						}
					}
				}
				if(StringUtils.isNull(paramsMap.get("appInfoId"))) {
					resultMap.put("success", false);
					resultMap.put("message", "appInfoId不能为空");
				}
				String filePath = "";
				if(uploadFile != null) {
					String logoRealPathDir = System.getProperty("catalina.base") + File.separator + "webapps" + propertiesUtils.getStylePath();
					File logoSaveFile = new File(logoRealPathDir);
					if (!logoSaveFile.exists()) {
					    logoSaveFile.mkdirs();
					}
					uploadFile.write(new File(logoRealPathDir,fileName));
					filePath = propertiesUtils.getStylePath() + fileName;
				}
				paramsMap.put("filePath", filePath);
				//更新用户扩展信息
				resultMap = appService.updateStyleUrl(paramsMap);
	    	}
		} catch (Exception e) {
			logger.error("更新应用自定义样式失败,失败原因:"+e);
			resultMap.put("success", false);
			resultMap.put("message", "更新应用自定义样式失败");
			return resultMap;
		}
		return resultMap;
	}
}
